﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：ApiSendMessageReposiory.cs
// 功能描述：TongTongMall.MallWeb.ApiRepository
// 
// Create User：jym 2017/02/28
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using TongTongMall.MallWeb.ApiRepository.Domain;
using TongTongMall.MallWeb.ApiRepository.Domain.Exceptions;
using TongTongMall.MallWeb.ApiRepository.Domain.Logger;
using TongTongMall.MallWeb.Core;
using TongTongMall.MallWeb.Core.IApiRepositories;
using TongTongMall.MallWeb.Core.Instance;
using TongTongMall.MallWeb.Core.SupportDomain.Models;
using TongTongMall.Timing;

namespace TongTongMall.MallWeb.ApiRepository.Repositories
{
    public class ApiSendMessageReposiory : IApiSendMessageReposiory
    {
        private readonly IApiContext _apiContext;
        private readonly IEncryptService _encryptService;
        public ApiSendMessageReposiory(
            IApiContext apiContext,
            IEncryptService encryptService)
        {
            _apiContext = apiContext;
            _encryptService = encryptService;
        }

        public async Task<bool> SendMessageAsync(SendMessageValueObject valueObject)
        {
            var timestamp = _encryptService.ConvertDateTimeToUinx(Clock.Now);
            var password = _encryptService.Md5Encrypt(
                $"{valueObject.MainMessagePwd}_{timestamp}_topsky");
            IDictionary<string, StringContent> msgData = new Dictionary<string, StringContent> {
                { "cpid", new StringContent($"{valueObject.MainMessageCPID}") },
                { "password", new StringContent($"{password}") },
                { "channelid", new StringContent($"{valueObject.MainMessageChannelID}") },
                { "tele", new StringContent($"{string.Join(",", valueObject.Mobile)}") },
                { "msg", new StringContent($"{Regex.Replace(valueObject.MsgContent, @"^(【.+?】)", string.Empty, RegexOptions.IgnoreCase)}") },
                { "timestamp",new StringContent( $"{timestamp}") }
            };
            var isSendSuccess = false;
            try
            {
                var result = await _apiContext.PostAsync<string>(valueObject.MainMessageUrl, msgData, typeof(string));
                if (result != null && result.StartsWith("success:"))
                {
                    isSendSuccess = true;
                }
                ApiLogHelper.Logger.Debug($"{JsonConvert.SerializeObject(valueObject)}\r\nResponse:{result}");
            }
            catch (Exception ex)
            {
                ApiLogHelper.LogException(ex);
                // ignored
            }
            if (!isSendSuccess)
            {
                //启用备用发送短信模式
                IDictionary<string, string> backMsgData = new Dictionary<string, string> {
                    { "mobile", $"{valueObject.Mobile}" },
                    { "apikey", $"{valueObject.BackMessageApiKey}" },
                    { "text", $"{valueObject.MsgContent}" }
                };
                try
                {
                    var result = await _apiContext.PostAsync<JObject>(valueObject.BackMessageUrl, new FormUrlEncodedContent(backMsgData));
                    if (result != null)
                    {
                        isSendSuccess = true;
                    }
                }
                catch (Exception ex)
                {
                    ApiLogHelper.LogException(ex);
                    // ignored
                }
            }
            return isSendSuccess;
        }
    }
}
